#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: SqlFormat.py
@Author: lijk34925 
@Date: 2024/8/8 17:07
@desc: SQL格式化脚本，DBeaver外挂
"""

import sys
import sqlparse
import io


def sql_formatter(sql):
    res = sqlparse.format(
        sql,
        keyword_case="upper",
        identifier_case="upper",
        truncate_strings=100,
        reindent_aligned=True,
        comma_first=False,
        wrap_after=60,
    )
    return res


if __name__ == "__main__":
    filepath = sys.argv[1]
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
    with open(filepath, "r", encoding="utf-8") as f:
        read_sql = f.read()
        for sql in read_sql.split(";"):
            s = sql.replace("\n", " ").strip()
            if len(s) != 0:
                s = sql_formatter(s) + ";\n"
                print(s)
